package Pool;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

import javafx.concurrent.Task;

public class ForiJoinPoolDemo {
    public static void main(String[] args) {
        MyTask task = new MyTask(0, 100);
        ForkJoinPool pool = new ForkJoinPool();
        ForkJoinTask<Integer> forkJoinTask =  pool.submit(task);
        try {
            Integer result = forkJoinTask.get();
            System.out.println("结果为： "+ result);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } finally{
            pool.shutdown();
        }
    }
}
// 计算一个问题，计算从 1 到 100 的和
// 但是每次计算的跨度不超过 10 个数字
class MyTask extends RecursiveTask<Integer>{
    // 规定跨度
    private static final Integer VALUE = 10;
    private int start;
    private int end;
    private int result;

    // 创建有参数构造
    public MyTask(int start, int end){
        this.start = start;
        this.end = end;
    }
    // 拆分计算逻辑
    @Override
    protected Integer compute() {
        if(end - start <= 10){
            for (int i = start; i <= end; i++) {
                result += i;
            }
        } else{
            // 获取中间
            int mid = (start + end) / 2;
            MyTask task01 = new MyTask(start, mid);
            MyTask task02 = new MyTask(mid, end);
            // 开始拆分
            task01.fork();
            task02.fork();
            result = task01.join() + task02.join();
        }
        return result;
    }
    
}
